package com.weilele.mvvm.utils.activity

import android.app.Activity
import android.content.res.Resources
import android.graphics.Color
import android.view.Window
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import com.weilele.mvvm.base.livedata.appCompatActivity

/**
 * 状态栏文字颜色，只有白色和黑色
 */
fun Activity.isStatusBarBlackTextColor(isBlackStatusBarTextColor: Boolean) {
    window.isStatusBarBlackTextColor(isBlackStatusBarTextColor)
}

/**
 * 状态栏文字颜色，只有白色和黑色
 */
fun Fragment.isStatusBarBlackTextColor(isBlackStatusBarTextColor: Boolean) {
    appCompatActivity?.isStatusBarBlackTextColor(isBlackStatusBarTextColor)
}

/**
 * 状态栏文字颜色，只有白色和黑色
 */
fun Window.isStatusBarBlackTextColor(isBlackStatusBarTextColor: Boolean) {
    WindowCompat.getInsetsController(this, decorView)?.apply {
        isAppearanceLightStatusBars = isBlackStatusBarTextColor
    }
}

/**
 * 透明状态栏
 */
fun Activity.transparentStatusBar(isBlackStatusBarTextColor: Boolean? = null) {
    window.transparentStatusBar(isBlackStatusBarTextColor)
}

/**
 * 透明状态栏
 */
fun Fragment.transparentStatusBar(isBlackStatusBarTextColor: Boolean? = null) {
    appCompatActivity?.transparentStatusBar(isBlackStatusBarTextColor)
}

/**
 * 透明状态栏，不处理导航栏
 */
fun Window.transparentStatusBar(isBlackStatusBarTextColor: Boolean? = null) {
    //预留导航栏的空间
    ViewCompat.setOnApplyWindowInsetsListener(decorView) { v, insets ->
        val navigationBarHeight =
            insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom
        decorView.updatePadding(bottom = navigationBarHeight)
        insets
    }
    //设置系统不要给状态栏和导航栏预留空间，否则无法透明状态栏
    WindowCompat.setDecorFitsSystemWindows(this, false)
    //设置状态栏颜色透明
    statusBarColor = Color.TRANSPARENT
    //处理状态栏文字颜色
    isBlackStatusBarTextColor?.let {
        isStatusBarBlackTextColor(isBlackStatusBarTextColor)
    }
}

/**
 * 获取状态栏高度
 */
fun Resources.getStatusBarHeight(): Int {
    val resourceId = getIdentifier("status_bar_height", "dimen", "android");
    return getDimensionPixelOffset(resourceId)
}

/**
 * 获取导航栏高度
 */
fun Resources.getNavigationBarHeight(): Int {
    val resourceId = getIdentifier("navigation_bar_height", "dimen", "android");
    return getDimensionPixelSize(resourceId)
}
